<?php


namespace Catmes\LayAdmin\Components;


use Catmes\LayAdmin\Components\LayJs\JsAjax;
use Catmes\LayAdmin\Components\LayJs\JsOpenUrl;
use Catmes\LayAdmin\helpers\HtmlHelper;

class TableToolbarBtn
{
    const TYPE_OPEN_GET = 'OPEN_GET';
    const TYPE_AJAX_POST = 'AJAX_POST';
    const TYPE_REDIRECT_TO = 'REDIRECT_TO';

    protected $actionType = self::TYPE_OPEN_GET;

    protected $eventName;
    protected $title='跳转';
    protected $msg = '确定操作？';
    protected $btnCssClasses = ['layui-btn', 'layui-btn-sm'];
    protected $btnHtml;

    /* @var Table $table */
    protected $table;

    protected $url;

    public function __construct(Table $table, $url)
    {
        $this->table = $table;
        if(strpos($url, "\"")===false && strpos($url, "'")===false){
            // url 字符串， 不包含 单引号'或双引号"， 则自动在字符串两边加双引号"。
            $url = "\"" . $url . "\"";
        }
        $this->url = $url;
    }

    protected function getBtn($content='添加', $event='add', $cssClasses=[]):self{
        $this->eventName = $event;
        $options = ['lay-event'=>$this->eventName, 'class'=>$this->btnCssClasses];
        if(!empty($cssClasses)){
            HtmlHelper::addCssClass($options, $cssClasses);
        }
        $this->btnHtml = HtmlHelper::button($content, $options);
        return $this;
    }

    public function btnCreate($content='添加', $cssClasses=[], $event='add'):self{
//        <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
        $cssClasses = empty($cssClasses) ? ['layui-btn-normal', 'data-add-btn'] : $cssClasses;
        return $this->btnOpenByUrl($content,$cssClasses, $event);
    }

    public function btnDelete($content='删除', $cssClasses=[], $event='delete'):self{
        // <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
        $cssClasses = empty($cssClasses) ? ['layui-btn-danger', 'data-delete-btn'] : $cssClasses;
        return $this->btnPostToUrl($content, $cssClasses, $event);
    }

    public function btnPostToUrl($content, $cssClasses=[], $event=''):self{
        $this->actionType = self::TYPE_AJAX_POST;
        $event = empty($event) ? 'post'.mt_rand(111,999) : $event;
        return $this->getBtn($content, $event, $cssClasses);
    }
    public function btnOpenByUrl($content, $cssClasses=[], $event=''):self{
        $this->actionType = self::TYPE_OPEN_GET;
        $event = empty($event) ? 'open'.mt_rand(111,999) : $event;
        return $this->getBtn($content, $event, $cssClasses);
    }
    public function btnRedirectToUrl($content, $cssClasses=[], $event=''):self{
        $this->actionType = self::TYPE_REDIRECT_TO;
        $event = empty($event) ? 'redirect'.mt_rand(111,999) : $event;
        return $this->getBtn($content, $event, $cssClasses);
    }

    public function render():string{
        return $this->btnHtml;
    }

    public function __toString(){
        return $this->render();
    }

    public function renderJs():string{
        $jsStr = '';
        switch ($this->actionType){
            case self::TYPE_OPEN_GET:
                $jsStr = $this->jsStrGet();
                break;
            case self::TYPE_AJAX_POST:
                $jsStr = $this->jsStrPost();
                break;
            case self::TYPE_REDIRECT_TO:
                $jsStr = $this->jsStrRedirect();
                break;
            default:
                $jsStr = '';
        }
        return $jsStr;
    }

    protected function jsStrRedirect():string{
        return <<<JSPTL
            if (obj.event === '{$this->eventName}') {
                window.location.href={$this->url}
            }
JSPTL;
    }

    protected function jsStrGet():string{
        $openUrlLayer = new JsOpenUrl($this->url, $this->title);
        $openUrlLayer->setEndFunc($this->table->getJsReload());
        return <<<JSPTL
            if (obj.event === '{$this->eventName}') {
                {$openUrlLayer}
            }
JSPTL;
    }

    protected function jsStrPost():string{
        $tableId = $this->table->getTableId();
        $jsAjax = new JsAjax($this->url, ['items'=>'data','ids'=>'ids']);
        $jsAjax->setJsVars(['data','ids'])
            ->setSuccess(JsAjax::JS_RESPONSE.$this->table->getJsReload());

        return <<<JSTPL
            if (obj.event === '{$this->eventName}') {
                var checkStatus = table.checkStatus('{$tableId}')
                , data = checkStatus.data;
                var ids = [];
                for(var i=0; i<data.length; i++){
                    if(data[i].hasOwnProperty('id')){
                        ids.push(data[i].id);
                    }
                }
                layer.confirm('{$this->msg}', function (index) {
                    {$jsAjax}
                    // AJAX异步操作，此处重载数据，不会生效
                    layer.close(index);
                    return false;
                });

            }
JSTPL;

    }


}
